using FreeSql.DataAnnotations;

namespace SumerCoreDevOps.Domain.Entities;

/// <summary>
/// 节点建立连接令牌（Join Token）
/// 用于节点首次注册时的一次性认证，具有时效性和使用次数限制
/// </summary>
[Table(Name = "node_join_tokens")]
[Index("idx_token", "Token", true)] // 唯一索引
public class NodeJoinToken
{
    /// <summary>
    /// ID
    /// </summary>
    [Column(IsPrimary = true, IsIdentity = true)]
    public long Id { get; set; }

    /// <summary>
    /// 令牌（唯一）
    /// </summary>
    [Column(StringLength = 64, IsNullable = false)]
    public string Token { get; set; } = null!;

    /// <summary>
    /// 令牌名称/描述
    /// </summary>
    [Column(StringLength = 200)]
    public string? Name { get; set; }

    /// <summary>
    /// 令牌用途描述
    /// </summary>
    [Column(StringLength = 500)]
    public string? Description { get; set; }

    /// <summary>
    /// 过期时间
    /// </summary>
    public DateTime? ExpiresAt { get; set; }

    /// <summary>
    /// 最大使用次数（null 表示无限制）
    /// </summary>
    public int? MaxUsageCount { get; set; }

    /// <summary>
    /// 已使用次数
    /// </summary>
    [Column(IsNullable = false)]
    public int UsedCount { get; set; } = 0;

    /// <summary>
    /// 是否启用
    /// </summary>
    [Column(IsNullable = false)]
    public bool IsEnabled { get; set; } = true;

    /// <summary>
    /// 是否已撤销
    /// </summary>
    [Column(IsNullable = false)]
    public bool IsRevoked { get; set; } = false;

    /// <summary>
    /// 撤销时间
    /// </summary>
    public DateTime? RevokedAt { get; set; }

    /// <summary>
    /// 撤销原因
    /// </summary>
    [Column(StringLength = 500)]
    public string? RevokeReason { get; set; }

    /// <summary>
    /// 撤销者
    /// </summary>
    [Column(StringLength = 100)]
    public string? RevokedBy { get; set; }

    /// <summary>
    /// 最后使用时间
    /// </summary>
    public DateTime? LastUsedAt { get; set; }

    /// <summary>
    /// 创建时间
    /// </summary>
    [Column(IsNullable = false)]
    public DateTime CreatedAt { get; set; } = DateTime.UtcNow;

    /// <summary>
    /// 创建者
    /// </summary>
    [Column(StringLength = 100)]
    public string? CreatedBy { get; set; }

    /// <summary>
    /// 更新时间
    /// </summary>
    public DateTime? UpdatedAt { get; set; }

    /// <summary>
    /// 使用此令牌注册的节点 ID 列表（JSON 数组）
    /// </summary>
    [Column(StringLength = -1)]
    public string? RegisteredNodeIds { get; set; }

    /// <summary>
    /// 检查令牌是否有效
    /// </summary>
    public bool IsValid()
    {
        // 检查是否启用
        if (!IsEnabled) return false;

        // 检查是否已撤销
        if (IsRevoked) return false;

        // 检查是否过期
        if (ExpiresAt.HasValue && ExpiresAt.Value < DateTime.UtcNow) return false;

        // 检查使用次数
        if (MaxUsageCount.HasValue && UsedCount >= MaxUsageCount.Value) return false;

        return true;
    }
}
